//编辑部门 begain
function replaceInputNode(obj) {
    var $obj = $(obj);
    var $obj_clone = $obj.clone(true);
    var depart = $obj_clone.find(".depart").html();
    var costcity = $obj_clone.children(".costcity").html();
    var formation = $obj_clone.children(".formation").html();
    var departattr = $obj_clone.children(".formation").next().html();
    var depart_num = $obj_clone.find(".depart_num").html();
    depart = xssFormation(depart);
    costcity = xssFormation(costcity);
    formation = xssFormation(formation);
    $bak_tr = $obj_clone.html();
    bak_json = {depart:depart,costcity:costcity,formation:formation};
    var id = $obj_clone.children("td:first").html();
    var validate = "{digits:true,range:[0,100000],messages:{digits:'请输入100000以内的数字',range:'请输入100000以内的数字'}}";

    var str = '<tr v="1" class="edit"><td>' + id + '</td><td class="depart"><input type="text" value="' + depart + '"/></td><td class="costcity"><input type="text" value="' + costcity + '"/></td><td class="formation"><input type="text" maxlength="6" value="' + formation + '"/></td><td>' + departattr + '</td><td ><i class="depart_num" style="display: none">' + depart_num + '</i><i style="visibility: visible;margin-top: 8px" class="delete icon-trash"></i></td> </tr>';
    $(obj).replaceWith(str);
    $("tbody tr").unbind();
    $(".delete.icon-trash").unbind();
    $("tbody tr").bind('click',trClickEvent);
    $(".delete.icon-trash").bind('click',showDelDialog);
    $("tbody tr").bind('mouseout', onMouseOutTr);
    $("tbody tr").bind('mouseover', onMouseOverTr);

}
function replaceTrNode(obj) {
    var $obj = $(obj);
    var $obj_clone = $obj.clone();
    var depart = $obj_clone.find(".depart").find("input").val();
    var costcity = $obj_clone.find(".costcity").find("input").val();
    var formation = $obj_clone.find(".formation").find("input").val();
    var id = $obj_clone.children("td:first").html();
    var departattr = $obj_clone.children(".formation").next().html();
    var depart_num = $obj_clone.find(".depart_num").html();
    depart = xssFormation(depart);
    costcity = xssFormation(costcity);
    formation = xssFormation(formation);

    var str = '<tr><td>' + id + '</td><td class="depart">' + depart + '</td><td class="costcity">' + costcity + '</td><td class="formation">' + formation + '</td><td>' + departattr + '</td><td><i class="depart_num" style="display: none">' + depart_num + '</i><i style="visibility: visible;margin-top: 8px" class="delete icon-trash"></i></td> </tr>';
    $(obj).replaceWith(str);
    $("tbody tr").unbind();
    $(".delete.icon-trash").unbind();
    $("tbody tr").bind('click',trClickEvent);
    $(".delete.icon-trash").bind('click',showDelDialog);
    $("tbody tr").bind('mouseout', onMouseOutTr);
    $("tbody tr").bind('mouseover', onMouseOverTr);
}
function xssFormation(str){
    var result;
    result = str.replace(/"/g,"&quot;");
    result = result.replace(/</g,"&lt;");
    result = result.replace(/>/g,"&gt;");

    return result;

}
function trClickEvent(event) {
    if ($(this).attr("v")) {
        //have clicked again!!!
        event.stopPropagation();
        return;
    }
    if ($("tr[v='1']").attr("v") == 1) {
        //have existed node that edit vale ,so,we shoud submit the value
        if (isInputEmpty()) {
            event.stopPropagation();
            return;
        }
        if ($("tr[v='1']").attr("v") == 1) {
            //have existed node that edit vale ,so,we shoud submit the value
            if (isInputEmpty()) {
                event.stopPropagation();
                return;
            }
            $old_node = $("tr[v='1']");

            if(!editDepartment($old_node)){//修改失败处理逻辑
                event.stopPropagation();
                return;
            }
            $old_node.css("background", "#ffffff");
            replaceTrNode($old_node);
            $old_node.attr("v", null);
            $(this).attr("v", 1);
            $(this).css("background", "#fdf0e6");
            replaceInputNode($(this));
            event.stopPropagation();
            return;
        }
        //this branch is the page begain,have no click history
        $(this).css("background", "#fdf0e6");
        $(this).attr("v", 1);
        replaceInputNode($(this));
        event.stopPropagation();
        return;
    }
    //this branch is the page begain,have no click history
    $(this).css("background", "#fdf0e6");
    $(this).attr("v", 1);
    replaceInputNode($(this));
    event.stopPropagation();
}
//删除部门
function delDepartment() {
    var $obj = $(".identity_del").parent().parent();
    var id = $.trim($obj.children("td:first").html());
    jQuery.ajax({
        url:delURL,
        data:{'id':id},
        type:'post',
        success:function (result) {
            var data = eval('(' + result + ')');
            if (data.errcode) {
                $obj.replaceWith("");
                var lableInfo = $(".btn.btn-small.disabled");
                lableInfo.html(lableInfo.html().replace(/(\d+)/, function () {
                    return parseInt(RegExp.$1) - 1;
                }));
                return;
            }
            $(".identity_del").removeClass("identity_del");
        }
    })
}
//jquery
//删除部门弹出事件
function showDelDialog(event) {
    var num = parseInt($(this).parent().children("i:first").html());
    if (num > 0) {
        $('#alertDialog').modal();//窗口显示
        return;
    }

    var id = $.trim($(this).parent().parent().children("td:first").html());
    var $obj = $(this);
    $obj.addClass("identity_del");
    $('#confirmDialog').modal();//窗口显示
    //取消按扭事件绑定
    event.stopPropagation();
    return;
}
function onMouseOverTr() {
    // $(this).css("background","#fdf0e6");
    var num =parseInt($.trim($(this).children("td:last").children(".depart_num").html()));
    if(num  == 0){
        $(this).children("td:last").children(".delete.icon-trash").css("display", "block");
    }

}
function onMouseOutTr() {
    $(this).children("td:last").children(".delete.icon-trash").css("display", "none");
}
$(document).ready(function () {
    //表格edit
    $("tbody tr").bind('click', trClickEvent);
    $("tbody tr").bind('mouseout', onMouseOutTr);
    $("tbody tr").bind('mouseover', onMouseOverTr);
    $(".delete.icon-trash").bind('click', showDelDialog);
    //删除确定
    $("#confirmDialog div .btn.btn-primary.delok").bind('click', function (event) {
        delDepartment();
        $("#confirmDialog").modal("hide");
        event.stopPropagation();
    });
    //删除取消
    $("#confirmDialog div  .btn.btn-small.delcancle").bind('click',function(event){
        $(".delete.icon-trash.identity_del").removeClass("identity_del");

    });
    $("#alertDialog div .btn.btn-small.btn-primary").bind('click',function(event){
        $("#alertDialog").modal('hide');
        $(".delete.icon-trash.identity_del").removeClass("identity_del");
        event.stopPropagation();


    });
    //body click
    $("body").bind("click", bodyClickEvent);
    function bodyClickEvent(event){
        if ($("tr[v='1']").attr("v") == 1) {
            if (isInputEmpty()) {
                event.stopPropagation();
                return;
            }
            var $old_node = $("tr[v='1']");
            var result = editDepartment($old_node);
            if (!result) {
                event.stopPropagation();
                return;
            }
            replaceTrNode($old_node);
            $old_node.css("background", "#ffffff");

        }
    }
    //删除取消
    $(".btn.btn-success").bind('click', function () {
        $(".identity_del").removeClass("identity_del");
    });
    //绑定添加部门的事件，以及ajax 请求
    $("#city").bind('click', selCity);
    $("#skill").bind('click', selBuit);

    $("#departForm").validate({
        submitHandler:function (form) {
            $.post(addURL, $(form).serialize(), function (data) {
                var data = eval('(' + data + ')');
                var msg = data.msg ? data.msg : $('#depart').val() + '添加成功！';
                $('#err').text(msg).show();
                setTimeout(function () {
                    $('#err').hide().text('')
                }, 3000);
            });
        },
        errorPlacement:function (error, element) {
            if (element.is(":radio"))
                error.appendTo(element.parent().next().next()); else if (element.is(":checkbox"))
                error.appendTo(element.next()); else
                element.parent().append(error);
        },
        errorClass:"invalid"
    });

});
//输入框存在空处理逻辑 begain
//存在空，返回true
//不存在空，返回false
function isInputEmpty() {
    depart = $.trim($(".depart input").val());
    formation = $.trim($(".formation input").val());
    costcity = $.trim($(".costcity input").val());
    int_formation = parseInt(formation);
    //为空验证 begain
    if (!depart || !formation || !costcity) {
        if (!$.trim($(".depart input").val())) {
            inputError('depart');
            return true;
        }
        if (!$.trim($(".formation input").val()) || int_formation < 0) {
            inputError('formation');
            return true;
        }
        if (!$.trim($(".costcity input").val())) {
            inputError('costcity');
            return true;
        }
    }
    if (int_formation < 0) {
        inputError('formation');
        return true;
    }
    //验证foramiton 为整数

    var   re   =   /^[0-9]*[1-9][0-9]*$/;;
    if(formation.match(re)== null)
    {
        inputError('formation');
        return true;
    }
    if(formation.indexOf('.')>0){
        inputError('formation');
        return true;
    }

    //为空验证end
    return false;
}
function inputError(class_name) {
    var div_begain = '<div class="control-group error"><td class="' + class_name + ' controls">';
    var div_end = '<input type="text" value=""></a></td></div>';
    var html = div_begain + div_end;
    var var_p = "." + class_name + " input";
    $(var_p).parent().html(html);

}
//输入框存在空处理逻辑 end

function editDepartment($obj) {
    var id = $obj.children("td").first().html();
    var result;
    if (isInputEmpty()) {
        replaceTrNode($obj);
        return;
    }
    if(depart == bak_json.depart && formation == bak_json.formation && costcity == bak_json.costcity)//value is not change
    {
        return true;
    }
    jQuery.ajax({
        async:false,
        url:editURL,
        data:{'id':id,'depart':depart,'formation':formation,'costcity':costcity},
        type:'post',
        success:function (data) {
            var data = eval('(' + data + ')');
            if(data.errcode){
                result = true;
                return;
            }
            $("#alertDialog .modal-body").html(data.msg);
            $("#alertDialog").modal();

            result = false;
            return;

        }
    });
    return result;
}
//编辑部门 end

function selCity() {
    var city = $('#city').val();
    if (city!='-1') {
        $("#cost").val(city);
    }
}
function selBuit() {
    $("#skill").change(function () {
        var buit = $("#skill option:selected").text();
        if($("#skill").val()!='-1'){
            if (buit) {
                $("#depart").val(buit);
                $("#depart").parent().find('label').text('');
            }
        }

    });
}
